
package com.be.beadmin.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.dto.output.UserEx;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.dto.input.UserWorkHourInfoDto;
import com.be.beadmin.product.dto.output.UserWorkHourInfoEx;
import com.be.beadmin.product.entity.ProductManufactInfor;
import com.be.beadmin.product.entity.UserWorkHourInfo;
import com.be.beadmin.product.entity.UserWorkHourInfo_;
import com.be.beadmin.product.entity.WrokingHoursOverView;
import com.be.beadmin.product.mapper.UserWorkHourInfoMapper;
import com.be.beadmin.product.mapper.UserWorkHourInfoMapperEx;
import com.be.beadmin.product.repository.UserWorkHourInfoRepository;
import com.be.beadmin.product.repository.WrokingHoursOverViewRepository;
import com.be.beadmin.product.service.UserWorkHourInfoService;
import com.be.beadmin.service.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zjm
 * @description 服务实现
 * @date 2023-11-22
 **/
@Service
@RequiredArgsConstructor
public class UserWorkHourInfoServiceImpl implements UserWorkHourInfoService {
    @Autowired
    private WrokingHoursOverViewRepository wrokingHoursOverViewRepository;
    @Autowired
    private UserWorkHourInfoRepository userWorkHourInfoRepository;
    @Autowired
    private UserWorkHourInfoMapper userWorkHourInfoMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserWorkHourInfoMapperEx userWorkHourInfoExMapper;

    @Override
    public Page<UserWorkHourInfoEx> getUserWorkHourInfoByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<UserWorkHourInfo> page = userWorkHourInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(UserWorkHourInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(UserWorkHourInfo_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<UserWorkHourInfoEx> page1 = page.map(userWorkHourInfoExMapper::toEntity);
        return page1;

    }

    @Override
    public void addUserWorkHourInfo(UserWorkHourInfoDto userWorkHourInfoDto) {
        UserWorkHourInfo result = userWorkHourInfoRepository.findUserWorkHourInfoByIdAndDelete(userWorkHourInfoDto.getId(), 0);
        if (ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("UserWorkHourInfo已存在,请重新查询");
        }
        UserWorkHourInfo userWorkHourInfo = userWorkHourInfoMapper.toEntity(userWorkHourInfoDto);
        userWorkHourInfoRepository.save(userWorkHourInfo);
    }

    @Override
    public void updateUserWorkHourInfo(UserWorkHourInfoDto userWorkHourInfoDto) {
        UserWorkHourInfo userWorkHourInfo = userWorkHourInfoRepository.findUserWorkHourInfoById(userWorkHourInfoDto.getId());
        userWorkHourInfo = userWorkHourInfoMapper.toEntity(userWorkHourInfoDto);
        userWorkHourInfoRepository.save(userWorkHourInfo);
    }


    @Override
    public void delUserWorkHourInfo(String id) {
        UserWorkHourInfo userWorkHourInfo = userWorkHourInfoRepository.findUserWorkHourInfoById(id);
        userWorkHourInfo.setDelete(1);
        userWorkHourInfoRepository.save(userWorkHourInfo);
    }

    @Override
    public void delUserWorkHourInfos(List<String> ids) {
    }

    /**
     * 获取当前用户的工序计时信息
     *
     * @param request
     * @return
     */
    @Override
    public UserWorkHourInfo getUserWorkHourInfo(HttpServletRequest request, String processId) {
        UserEx userEx = userService.viewBaseInfo(request);
        UserWorkHourInfo userWorkHourInfo = userWorkHourInfoRepository.findUserWorkHourInfoByUserIdAndProcessIdAndDelete(userEx.getId(), processId, 0);
        return userWorkHourInfo;
    }

    public UserWorkHourInfo getUserWorkHourInfo(UserEx userEx, String processId) {
        UserWorkHourInfo userWorkHourInfo = userWorkHourInfoRepository.findUserWorkHourInfoByUserIdAndProcessIdAndDelete(userEx.getId(), processId, 0);
        return userWorkHourInfo;
    }


    @Override
    public int viewProcessState(ProductManufactInfor productManufactInfor) {
        int count = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndDelete(productManufactInfor.getProcessId(), 0, 0);
//        int count = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndDelete(productManufactInfor.getProcessId(), 0, 0);
        if (count == 0) { // 也就是要不没开始   要么是都是0 也就是未开始状态
            return 0;
        }
        int count2 = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndDelete(productManufactInfor.getProcessId(), 3, 0);
        if (count2 == 0) { // 不为3的 个数为0， 也就是 全为3， 说明已经都结束了
            return 3;
        }
        return 1;// 其他情况是执行中的状态， 没有暂停这个；

    }

    @Override
    public void startTiming(UserWorkHourInfo newUWHI) {
        if (newUWHI.getProcessStatus() != 1) throw new BeadminException("工序未开始执行");
        WrokingHoursOverView wrokingHoursOverView = wrokingHoursOverViewRepository.findWrokingHoursOverViewByProcessIdAndUserIdAndDelete(newUWHI.getProcessId(), newUWHI.getUserId(), 0);
        WrokingHoursOverView newWHO;
        if (wrokingHoursOverView != null) {
            newWHO = wrokingHoursOverView;
        } else {
            newWHO = new WrokingHoursOverView();
        }
        newWHO.setCurrStartTime(new Date());
        newWHO.setTimeFlag(1);
        newWHO.setOperatorId(newUWHI.getUserName());  // 把当前用户加进去
        newWHO.setProcessId(newUWHI.getProcessId());
        newWHO.setUserId(newUWHI.getUserId());
        wrokingHoursOverViewRepository.save(newWHO);
    }

    @Override
    public void finishTiming(UserWorkHourInfo userWorkHourInfo,Date findate) {
        WrokingHoursOverView wrokingHoursOverView = wrokingHoursOverViewRepository.findWrokingHoursOverViewByProcessIdAndUserIdAndDelete(userWorkHourInfo.getProcessId(), userWorkHourInfo.getUserId(), 0);
        if (wrokingHoursOverView == null) throw new BeadminException("未找到当前用针对该工序的计时");
        // 上次开始时间
        Date startTime = wrokingHoursOverView.getCurrStartTime();
        Float secondTime = DateUtil.computeDateDuringBySecond(startTime, findate); // 以秒计算
        wrokingHoursOverView.setTimeFlag(0);
//            newWHO.setOperatorId("当前用户");  // 把当前用户加进去
        wrokingHoursOverView.setProcessId(userWorkHourInfo.getProcessId());
        wrokingHoursOverView.setAccWorkHours(secondTime);
        if (wrokingHoursOverView.getSumWorkHours() == null) {
            wrokingHoursOverView.setSumWorkHours(secondTime);
        } else {
            wrokingHoursOverView.setSumWorkHours(wrokingHoursOverView.getSumWorkHours() + secondTime);

        }
        wrokingHoursOverViewRepository.save(wrokingHoursOverView);
        userWorkHourInfo.setManufactWorkhour(wrokingHoursOverView.getSumWorkHours());

    }

    @Override
    public int viewProcessStateExceptSelf(ProductManufactInfor productManufactInfor, UserEx userEx) {
//        int count = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndUserIdNotAndDelete(productManufactInfor.getProcessId(), 0, userEx.getId(), 0);
//        int count = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndDelete(productManufactInfor.getProcessId(), 0, 0);
//        if (count == 0) { // 也就是要不没开始   要么是都是0 也就是未开始状态
//            return 0;
//        }
        int count2 = userWorkHourInfoRepository.countUserWorkHourInfoByProcessIdAndProcessStatusNotAndUserIdNotAndDelete(productManufactInfor.getProcessId(), 3, userEx.getId(), 0);
        if (count2 == 0) { // 不为3的 个数为0， 也就是 全为3， 说明已经都结束了
            return 3;
        }
        return 1;// 其他情况是执行中的状态， 没有暂停这个；
    }

    @Override
    public void pauseTiming(UserWorkHourInfo userWorkHourInfo) {

    }
}